//
//  audio_encoder.hpp
//  Recoder
//
//  Created by dg on 2023/12/13.
//

#ifndef audio_encoder_hpp
#define audio_encoder_hpp

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#ifndef UINT64_C
#define UINT64_C(value) __CONCAT(value, ULL)
#endif

#define byte uint8_t

#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))

#define LOGI(...)  printf("  "); printf(__VA_ARGS__); printf("\t -  <%s> \n", LOG_TAG);

#ifndef PUBLISH_BITE_RATE
#define PUBLISH_BITE_RATE 64000
#endif


extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libswresample/swresample.h"
}

class AudioEncoder {
public:
    // 初始化
    // bitRate 比特率 也就是最终编码出来的文件的码率
    int init(int bitRate, int channels, int sampleRate, int bitsPerSample, const char* aacFilePath, const char *codec_name);
    int init(int bitRate, int channels, int bitesPerSample, const char *aacFilePath, const char *codec_name);

    // 编码
    void encode(byte *buffer, int size);
    // 销毁
    void destory();
    
private:
    AVFormatContext *_avFormatContext;
    AVCodecContext *_codecContext;
    AVStream *_audioStream;
    AVFrame *_inputFrame;
    AVPacket *_outputPkt;
    
    bool _isWriteHeaderSuccess;
    double _duration;
    
    
    int _bufferSize;
    uint8_t *_samples;
    int _sampleCursor;
    
    int _publishBitRate;
    int _audioChannels;
    int _audioSampleRate;
    
    int _totalSWRTimeMills;
    int _totalEncodeTimeMills;
    
    int alloc_avframe();
    int alloc_audio_stream(const char *codec_name);
    int encodePacket();
    bool checkSampleFMT(const AVCodec *codec, enum AVSampleFormat fmt);
    int bestSampleRate(const AVCodec *codec);
    int selectChannelLayout(const AVCodec *codec);
};

#endif /* audio_encoder_hpp */
